var fs = require('fs')

function PackageDb(dbfile) {
  if (!(this instanceof PackageDb)) {
    return new PackageDb(dbfile)
  }
  this.dbfile = dbfile
  this.pkgnames = []
}

PackageDb.prototype.load = function() {
  this.pkgnames = []
  try {
    var data = fs.readFileSync(this.dbfile, 'utf8')
    var word = ''
    for (var c of data) {
      if (c === '\n') {
        if (word.length > 0) {
          this.pkgnames.push(word)
          word = ''
        }
      } else {
        word += c
      }
    }
    if (word.length > 0) {
      this.pkgnames.push(word)
      word = ''
    }
  } catch (e) {
    if (e.code !== 'ENOENT') {
      throw e
    }
  }
  return this
}

PackageDb.prototype.dump = function() {
  fs.writeFileSync(this.dbfile, this.pkgnames.join('\n'))
  return this
}

PackageDb.prototype.add = function(name, version) {
  this.pkgnames.push(name + '@' + version)
  return this
}

PackageDb.prototype.contains = function(name, version) {
  for (var n of this.pkgnames) {
    if (n === (name + '@' + version)) {
      return true
    }
  }
  return false
}

PackageDb.prototype.clean = function() {
  this.pkgnames = []
  this.dump()
  return this
}

module.exports = PackageDb